package com.example.bluetoothtest;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.service.voice.VoiceInteractionSession;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    //常量
    private static final int REQ_PERMISSION_CODE = 1;

    //实例化蓝牙控制器
    public BlueToothController btController = new BlueToothController();

    //弹窗
    private Toast mToast;

    //蓝牙权限列表
    public ArrayList<String> requestList = new ArrayList<>();

    public ArrayAdapter adapter1;

    //定义一个列表，存蓝牙设备的地址
    public ArrayList<String> arrayList = new ArrayList<>();

    //定义一个列表，存蓝牙设备地址，用于显示
    public ArrayList<String> deviceName = new ArrayList<>();


    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        //获取listView控件
        ListView listView = findViewById(R.id.bluetooth_list);
        //实例化ArrayAdapter对象
        adapter1 = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, deviceName);
        //添加到listView控件中
        listView.setAdapter(adapter1);

        //处理listView点击事件
        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            try {
                //获取点击项的文本内容
                CharSequence content = ((TextView) view).getText();
                String con = content.toString();
                //解析内容（根据换行符将其分为三个元素，["蓝牙名称：xxx", "蓝牙地址：xx：xx：xx：xx", "连接状态：xxx"]）
                String[] conArray = con.split("\n");
                if (conArray.length < 2) {
                    showToast("无效的设备信息!");
                    return;
                }
                //蓝牙名称
                String bluetooth_name = conArray[0].substring(5);
                //蓝牙地址
                String bluetooth_address = conArray[1].substring(6).trim();

                //页面带参数跳转
                Intent intent = new Intent(MainActivity.this, ConnectAndDisconnectActivity.class);
                intent.putExtra("bluetooth_name", bluetooth_name);
                intent.putExtra("bluetooth_address", bluetooth_address);
                startActivity(intent);

            } catch (Exception e) {
                showToast("发生错误：" + e.getMessage());
                Log.e("BluetoothError", "Error handling device bonding", e);
            }
        });


        //绑定按钮点击事件
        Button get_bt_list = findViewById(R.id.get_bluetooth_list);
        get_bt_list.setOnClickListener(v -> {
            //获取蓝牙权限
            getPermission();
            //初始化列表
            deviceName.clear();
            arrayList.clear();

            //异步获取已配对的蓝牙设备列表
            new Thread(() ->{
               ArrayList<BluetoothDevice> bluetoothDevices = btController.getBondedDeviceList();
               if (bluetoothDevices != null) {
                   runOnUiThread(() -> {
                       Toast.makeText(this, "找到 " + bluetoothDevices.size() + "个已配对的设备", Toast.LENGTH_SHORT).show();
                       TextView connected_textView = findViewById(R.id.connected_bluetooth_textView);
                       connected_textView.setVisibility(View.VISIBLE);
                       for (BluetoothDevice device : bluetoothDevices) {
                           //获取已配对设备蓝牙地址
                           String address = device.getAddress();
                           //获取已配对设备蓝牙名称
                           String name = device.getName();
                           if (address == null) {
                               address = "未知地址";
                           }
                           if (name == null) {
                               name = "未知名称";
                           }
                           //将地址添加到存储蓝牙地址的列表中
                           arrayList.add(address);
                           switch (device.getBondState()) {
                               case BluetoothDevice.BOND_BONDED:
                                   deviceName.add("蓝牙名称：" + name + "\n" + "MAC地址：" + address + "\n" + "连接状态：已配对" + "\n");
                                   break;
                               case BluetoothDevice.BOND_NONE:
                                   deviceName.add("蓝牙名称：" + name + "\n" + "MAC地址：" + address + "\n" + "连接状态：未配对" + "\n");
                                   break;
                               default:
                                   deviceName.add("蓝牙名称：" + name + "\n" + "MAC地址：" + address + "\n" + "连接状态：未知" + "\n");
                                   break;
                           }
                       }
                       adapter1.notifyDataSetChanged();
                   });
               } else {
                   runOnUiThread(() -> Toast.makeText(this, "未找到任何已配对设备", Toast.LENGTH_SHORT).show());
               }
            }).start();

        });
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//            return insets;
//        });
    }

    /**
     * 动态申请权限
     * 此方法用于根据设备的Android版本动态申请所需的权限
     * 在Android S及以上版本，需要申请蓝牙扫描、广告、连接以及位置权限
     * 如果请求列表不为空，则通过ActivityCompat.requestPermissions方法申请权限
     */
    public void getPermission(){
        // 检查设备的Android版本是否为S或以上
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            // 向请求列表添加Android S及以上版本所需的蓝牙和位置权限
            requestList.add(android.Manifest.permission.BLUETOOTH_SCAN);
            requestList.add(android.Manifest.permission.BLUETOOTH_ADVERTISE);
            requestList.add(android.Manifest.permission.BLUETOOTH_CONNECT);
            requestList.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
            requestList.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
            requestList.add(Manifest.permission.BLUETOOTH);
        }
        // 如果请求列表不为空，则执行权限请求
        if(requestList.size() != 0){
            ActivityCompat.requestPermissions(this, requestList.toArray(new String[0]), REQ_PERMISSION_CODE);
        }
    }

    /**
     * Toast弹窗显示
     * @param text  显示文本
     */
    public void showToast(String text){
        // 若Toast控件未初始化
        if( mToast == null){
            // 则初始化
            mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        }
        // 否则
        else{
            // 修改显示文本
            mToast.setText(text);
        }
        // 显示
        mToast.show();
    }
}